package com.gongyou.forum.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gongyou.common.entity.Result;
import com.gongyou.common.pojo.User;
import com.gongyou.common.utils.AuthUtil;
import com.gongyou.common.utils.AvaImgHanlderUtils;
import com.gongyou.forum.mapper.UserLoginMapper;
import com.gongyou.forum.service.UserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.UUID;


/**
 * @Author LiQuanPing
 * @Date 2021-03-23 16:22
 * @Version 1.8
 * @creed: ♂♂Talk is cheap,show me the code♀♀
 * * 用户登陆,注册,忘记密码 处理controller
 */
@Service
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    private UserLoginMapper userLoginMapper;

    @Value("${avaImg.imgPath}")
    private String path;

    @Value("${avaImg.qiniuAddress}")
    private String qiniuAddress;

    //用户登陆
    @Override
    public User login(User user) {
        String phone = user.getPhone();
        User user1 = userLoginMapper.selectOne(new QueryWrapper<User>().eq("phone", phone).eq("is_del", 0));
        return user1;
    }

    //根据手机号码判断用户是否注册
    @Override
    public boolean phoneIsReg(String phone) {
        User user = userLoginMapper.selectOne(new QueryWrapper<User>().eq("phone", phone));
        if (user != null) {
            return true;
        } else {
            return false;
        }
    }

    //用户注册
    @Override
    public void register(User user) throws IOException {
        String hashpw = BCrypt.hashpw(user.getPassword(), BCrypt.gensalt());
        user.setPassword(hashpw);
        String nickName = user.getNickName();
        String suffixName = ".png";
        String avaName = UUID.randomUUID().toString();
        AvaImgHanlderUtils.generateImg(nickName, path + nickName + suffixName, avaName + suffixName);
        user.setAvatarUrl(qiniuAddress + avaName + suffixName);
        userLoginMapper.insert(user);
    }

    //根据电话修改密码
    @Override
    public void editPasswordByPhone(User user) {
        user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
        userLoginMapper.update(user, new QueryWrapper<User>().eq("phone", user.getPhone()));
    }

    //微信登录
    @Override
    public Result weChatLogin(String code) {
        try {
            //通过第一步获得的code获取微信授权信息
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AuthUtil.APPID + "&secret="
                    + AuthUtil.APPSECRET + "&code=" + code + "&grant_type=authorization_code";
            JSONObject jsonObject = AuthUtil.doGetJson(url);
            String openid = jsonObject.getString("openid");
            String token = jsonObject.getString("access_token");
            String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + token + "&openid=" + openid
                    + "&lang=zh_CN";
            JSONObject userInfo = AuthUtil.doGetJson(infoUrl);

            System.out.println("userInfo==" + userInfo);

            //成功获取授权,以下部分为业务逻辑处理了，根据个人业务需求写就可以了
            if (userInfo != null && openid != null) {
                String nickname = userInfo.getString("nickname");
                String headimgurl = userInfo.getString("headimgurl");
                headimgurl = headimgurl.replace("\\", "");//头像
                //根据openid查询时候有用户信息
                return new Result(false, "登录失败");

            } else {
                return new Result(false, "登录失败");
            }
        } catch (Exception e) {
            return new Result(false, "登录失败");

        }
    }
}